package com.block.common.util.net;

import com.block.common.exception.BotApiException;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ok http请求工具类
 *
 * 
 * @date 2021/10/26 4:34 下午
 */
public class OkHttpUtil {

    private static Logger logger = LoggerFactory.getLogger(OkHttpUtil.class);
    private static final OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .callTimeout(30, TimeUnit.SECONDS)
            .build();

    /**
     * 执行请求
     *
     * @param url
     * @param builder
     * @return
     * @throws IOException
     */
    public static String execute(String url, UrlParamsBuilder builder) throws IOException {
        Request request = null;

        if (builder.hasHeaders()) {
            request = createRequest(url, builder, builder.getHeaders());
        } else {
            request = createRequest(url, builder);
        }
        String str = null;
        Response response = client.newCall(request).execute();
        if (response != null && response.body() != null) {
            str = response.body().string();
            response.close();
            return str;
        } else {
            throw new BotApiException(BotApiException.ENV_ERROR,
                    "[Invoking] Cannot get the response from server");
        }

    }


    private static Request createRequest(String url, UrlParamsBuilder builder) {
        String requestUrl = url;
        logger.info("请求数据信息:{},url:{}", builder.buildPostBody(), url);
        if (builder != null) {
            if (builder.hasFormParam()) {
                logger.info("请求form数据信息:{},url:{}", builder.buildFormBody(), url);
                return new Request.Builder().url(requestUrl).post(builder.buildFormBody())
                        .addHeader("Content-Type", "application/x-www-form-urlencoded").build();
            } else if (builder.hasPostParam()) {
                return new Request.Builder().url(requestUrl).post(builder.buildPostBody())
                        .addHeader("Content-Type", "application/json").build();
            } else if (builder.checkMethod("DELETE")) {
                return new Request.Builder().url(requestUrl)
                        .delete(builder.buildPostBody())
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        .build();
            } else if (builder.checkMethod("PUT")) {
                return new Request.Builder().url(requestUrl)
                        .put(builder.buildPostBody())
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        .build();
            } else {
                requestUrl+= builder.buildUrl();
                return new Request.Builder().url(requestUrl)
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        .build();
            }
        } else {
            return new Request.Builder().url(requestUrl).addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
        }
    }

    /**
     * 创建请求
     *
     * @param url     地址
     * @param builder 参数
     * @param headers headers
     * @return
     */
    private static Request createRequest(String url, UrlParamsBuilder builder, Map<String, String> headers) {
        String requestUrl = url;
        System.out.print(requestUrl);
        Request.Builder requestBuilder = null;
        logger.info("请求postbody数据信息:{},url:{}", builder.buildPostBody(), url);
        logger.info("请求head数据信息:{},url:{}", builder.getHeaders(), url);
        if (builder != null) {
            if (builder.hasFormParam()) {
                logger.info("请求form数据信息:{},url:{}", builder.buildFormBody(), url);
                requestBuilder = new Request.Builder().url(requestUrl).post(builder.buildFormBody())
                        .addHeader("Content-Type", "application/x-www-form-urlencoded");
                if (!headers.isEmpty()) {
                    for (String key : headers.keySet()) {
                        requestBuilder.addHeader(key, headers.get(key));
                    }
                }
                return requestBuilder.build();
            } else if (builder.hasPostParam()) {
                requestBuilder = new Request.Builder().url(requestUrl).post(builder.buildPostBody());
                requestBuilder.addHeader("Content-Type", "application/json");
                if (!headers.isEmpty()) {
                    for (String key : headers.keySet()) {
                        requestBuilder.addHeader(key, headers.get(key));
                    }
                }
                return requestBuilder.build();
            } else if (builder.checkMethod("DELETE")) {
                requestBuilder = new Request.Builder().url(requestUrl).delete(builder.buildPostBody());
                requestBuilder.addHeader("Content-Type", "application/x-www-form-urlencoded");
                if (!headers.isEmpty()) {
                    for (String key : headers.keySet()) {
                        requestBuilder.addHeader(key, headers.get(key));
                    }
                }
                return requestBuilder.build();
            } else if (builder.checkMethod("PUT")) {
                requestBuilder = new Request.Builder().url(requestUrl).put(builder.buildPostBody());
                requestBuilder.addHeader("Content-Type", "application/x-www-form-urlencoded");
                if (!headers.isEmpty()) {
                    for (String key : headers.keySet()) {
                        requestBuilder.addHeader(key, headers.get(key));
                    }
                }
                return requestBuilder.build();
            } else {
                requestBuilder.addHeader("Content-Type", "application/x-www-form-urlencoded");
                if (!headers.isEmpty()) {
                    for (String key : headers.keySet()) {
                        requestBuilder.addHeader(key, headers.get(key));
                    }
                }
                return requestBuilder.build();
            }
        } else {
            requestBuilder = new Request.Builder().url(requestUrl);
            requestBuilder.addHeader("Content-Type", "application/x-www-form-urlencoded");
            if (!headers.isEmpty()) {
                for (String key : headers.keySet()) {
                    requestBuilder.addHeader(key, headers.get(key));
                }
            }
            return requestBuilder.build();
        }
    }
}
